<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><#assign module="system/menus"><#assign moduleName="菜单">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="${base}/commonjs/ztree/demoStyle/demo.css" type="text/css">
<link rel="stylesheet" href="${base}/commonjs/ztree/zTreeStyle/zTreeStyle.css" type="text/css">
<script type="text/javascript" src="${base}/commonjs/jquery1.7.2/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="${base}/commonjs/ztree/jquery.ztree.core-3.2.min.js"></script>
<script type="text/javascript" src="${base}/commonjs/ztree/jquery.ztree.exedit-3.2.min.js"></script>
<script type="text/javascript" src="${base}/commonjs/jquery-forms.js"></script>
<script type="text/javascript" src="${base}/commonjs/jquery.select.js"></script>
<script type="text/javascript" src="${base}/commonjs/artDialog4/artDialog.source.js?skin=blue"></script>
<script type="text/javascript" src="${base}/commonjs/artDialog4/plugins/iframeTools.source.js"></script>
<title>${moduleName}列表</title>
<style type="text/css">
ul.ztree {
	margin-top: 10px;
	border: 1px solid #617775;
	background: #f0f6e4;
	width:220px;
	height:360px;
	overflow-y:scroll;
	overflow-x:auto;
}
</style>
<script type="text/javascript">
<!--
$(function(){
var setting = {
	edit: {
		drag: {
			autoExpandTrigger: true,
			prev: canDropPrev,
			inner: canDropInner,
			next: canDropNext
		},
		enable: true,
		showRemoveBtn: false,
		showRenameBtn: false
	},
	data: {
		simpleData: {
			enable: true
		}
	},
	callback: {
		beforeDrag: beforeDrag,
		beforeDrop: beforeDrop,
		beforeDragOpen: beforeDragOpen,
		onDrag: onDrag,
		onDrop: onDrop,
		onExpand: onExpand,
		onClick: onMenuItemClick
	}
};
function canDropPrev(treeId, nodes, targetNode) {
	var pNode = targetNode.getParentNode();
	if (pNode && pNode.dropInner === false) {
		return false;
	} else {
		for (var i=0,l=curDragNodes.length; i<l; i++) {
			var curPNode = curDragNodes[i].getParentNode();
			if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
				return false;
			}
		}
	}
	return true;
}
function canDropInner(treeId, nodes, targetNode) {
	if (targetNode && targetNode.dropInner === false) {
		return false;
	} else {
		for (var i=0,l=curDragNodes.length; i<l; i++) {
			if (!targetNode && curDragNodes[i].dropRoot === false) {
				return false;
			} else if (curDragNodes[i].parentTId && curDragNodes[i].getParentNode() !== targetNode && curDragNodes[i].getParentNode().childOuter === false) {
				return false;
			}
		}
	}
	return true;
}
function canDropNext(treeId, nodes, targetNode) {
	var pNode = targetNode.getParentNode();
	if (pNode && pNode.dropInner === false) {
		return false;
	} else {
		for (var i=0,l=curDragNodes.length; i<l; i++) {
			var curPNode = curDragNodes[i].getParentNode();
			if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
				return false;
			}
		}
	}
	return true;
}

var log, className = "dark", curDragNodes, autoExpandNode;
function beforeDrag(treeId, treeNodes) {
	className = (className === "dark" ? "":"dark");
	for (var i=0,l=treeNodes.length; i<l; i++) {
		if (treeNodes[i].drag === false) {
			curDragNodes = null;
			return false;
		} else if (treeNodes[i].parentTId && treeNodes[i].getParentNode().childDrag === false) {
			curDragNodes = null;
			return false;
		}
	}
	curDragNodes = treeNodes;
	return true;
}
function beforeDragOpen(treeId, treeNode) {
	autoExpandNode = treeNode;
	return true;
}
function beforeDrop(treeId, treeNodes, targetNode, moveType, isCopy) {
	className = (className === "dark" ? "":"dark");
	return true;
}
function onDrag(event, treeId, treeNodes) {
	className = (className === "dark" ? "":"dark");
	draggingNode = treeNodes[0];
	draggingParent = draggingNode.getParentNode();
	draggingPrev = draggingNode.getPreNode();
	draggingNext = draggingNode.getNextNode();
}
function onDrop(event, treeId, treeNodes, targetNode, moveType, isCopy) {
	className = (className === "dark" ? "":"dark");
	dropConfirm(treeNodes, targetNode, moveType);
}
function onExpand(event, treeId, treeNode) {
	if (treeNode === autoExpandNode) {
		className = (className === "dark" ? "":"dark");
	}
}

$.post("${base}/system/menus/list", {pageNo: 1, pageSize: 999}, function(json){
	//var zNodes = [];
	var menus = [];
		///////////////////////////////////////////////////////////////////////////////
		// id, name, parent, entry                                                   //
		// {                                                                         //
		//	  page: $ {pageNo},                                                      //
		//	  total: $ {totalCount},                                                 //
		//	  rows: [{                                                               //
		//		id: $ {id},                                                          //
		//		cell:[id, name, description, pId, pName, cId, cName, entry, seq]     //
		//	  },...                                                                  //
		//	  ]                                                                      //
		//  }		                                                                 //
		//  { id:33, pId:3, name:"随意拖拽 3-3"}                                      //
		///////////////////////////////////////////////////////////////////////////////
	for(var i=0; i<json.rows.length; i++){
		var row = json.rows[i].cell;
		var id = row[0];
		var cId = row[5]||0;
		var entry = row[7];
		var name = row[1]+"["+id+"]";
		if(!!cId){
			name += "["+cId+":"+entry+"]";
		}
		var seq = row[8];
		var menu = {
			id: id, 
			name: name, 
			pId: row[3]||0,
			cId: cId,
			seq: seq,
			subs: 0
		};
		if(!!cId){
			menu.dropInner = false;
		}
		menus.push(menu);
	}
	for(var i=0; i<menus.length; i++){
		for(var j=0; j<menus.length; j++){
			if(menus[i].id==menus[j].pId){
				menus[i].subs++;
				menus[j].parent = menus[i].name;
				menus[j].parentElement = menus[i];
			}
		}
	}
	var tree = $.fn.zTree.init($("#treeDemo"), setting, menus);
	var nodes = tree.getNodes();
    var len = nodes.length;
    if(len>0){
        var lastSub = nodes[len-1];
        nextSequence = Math.ceil(+lastSub.seq)+1;
    }else{
        nextSequence = 0;
    }
	initParams();
});//end of $.post

});//end of $(function(){...})

var parentNodeId = 0;//新建节点时应该赋予的父节点id
var parentNodeName = "";//新建节点时应该显示的父节点信息
var currentNodeId = 0;
var nextSequence = -1;
function onMenuItemClick(event, treeId, treeNode){
	//alert("id: "+treeNode.id+", pId: "+treeNode.pId+", seq: "+treeNode.seq);
	currentNodeId = treeNode.id;
	showEditMode(true, treeNode.subs);//切换右侧标题栏
	//这个地方计算的nextSequence肯定是有误的，应当看从哪里进行新建操作，然后确定nextSequence
	//nextSequence = treeNode.children==null?0:treeNode.children.length;
	if(treeNode.subs>0||treeNode.cId==0){//当前节点是目录或者可作为目录，则在当前节点下建立子菜单
		parentNodeId = treeNode.id||0;
		parentNodeName = treeNode.name||"";
		//这个地方用length应该是很不恰当的，应该看最后一个节点的sequence是多少，然后再加1
		//nextSequence = treeNode.children==null?0:treeNode.children.length;
		if(treeNode.children==null||treeNode.children.length==0){
			nextSequence = 0;
		}else{
			var lastSub = treeNode.children[treeNode.children.length-1];
			nextSequence = Math.ceil(+lastSub.seq)+1;
		}
	}else
	if(treeNode.parentElement!=null){//当前节点是叶子节点，则在当前节点的父节点下建立子节点
		parentNodeId = treeNode.parentElement.id||0;
		parentNodeName = treeNode.parentElement.name||"";
		var parentNode = treeNode.getParentNode();
		if(!!parentNode){
			var lastSub = parentNode.children[parentNode.children.length-1];
			nextSequence = Math.ceil(+lastSub.seq)+1;
		}else{
			var tree = $.fn.zTree.getZTreeObj("treeDemo");
			var nodes = tree.getNodes();
			var len = nodes.length;
			var lastSub = nodes[len-1];
			nextSequence = Math.ceil(+lastSub.seq)+1;
		}
	}else{//这是一个顶级的功能菜单。应该建立一个顶级的最新一个菜单。
		parentNodeId = 0;
		parentNodeName = "";
		var tree = $.fn.zTree.getZTreeObj("treeDemo");
        var nodes = tree.getNodes();
        var len = nodes.length;
        if(len>0){
        	var lastSub = nodes[len-1];
            nextSequence = Math.ceil(+lastSub.seq)+1;
        }else{
        	nextSequence = 0;
        }
	}
	//alert("nextSequence: "+nextSequence);
	//获取当前节点信息，将其放置在右侧编辑框中
	$.post("${base}/system/menus/"+treeNode.id, {}, function(menu){
		menu.parent = treeNode.parent;
		initForm(menu, treeNode.subs);
	});
}
var selectM;
var initedModuleId = 0;
var selectF;
function initParams(){
	selectM = $("#selectModules");
	selectF = $("#selectFunctions");
	selectM.createSelect("${base}/system/modules/list", {
		pageNo:1,pageSize:999
	}, function(row){
		return [row.id, row.cell[1]];
	}).change(function(){
		$("#input_func_id").val("");
		var selectedValue = $(this).val();
		if(+selectedValue>0){
			selectF.attr("disabled", false);
			if(selectedValue-initedModuleId!=0){
				selectF.get(0).options.length=1;
				initSelectC(selectedValue);
			}
		}else{
			selectF.val(0);
			selectF.attr("disabled", true);
		}
	});
	selectF.change(function(){
		var value = $(this).val();
		if(value==0){
			value = "";
		}
		$("#input_func_id").val(value);
	});
	
	//“保存”按钮事件
	$("#btadditem").bind("click", function(){
		var menuId = $("#input_id").val();//用来判断是新建（0）还是编辑（非0）
		var func = menuId>0?"编辑菜单信息":"添加菜单信息";
		var action = +menuId>0?"${base}/system/menus/edit":"${base}/system/menus/add";
		$("#additemform").ajaxForm({//提交表单
			dataType: "json",
			url: action,
			success: function(json){
				if(!json.success){
					var title = func + "失败";
					art.dialog({
						title: title,
						icon: "error",
						content: json.err,
						width: 400,
						height: 250,
						background: '#EEE', // 背景色
						opacity: 0.05,	// 透明度
						lock: true,
						ok: true
					});
				}else{
					refreshMenuTree(json.id);//刷新树，给出当前节点的ID
					var title = func + "成功";
					art.dialog({
						title: title,
						icon: "succeed",
						content: title+", id="+json.id,
						width: 250,
						height: 150,
						background: '#EEE', // 背景色
						opacity: 0.05,	// 透明度
						lock: true,
						ok: true
					});
				}
			}
		});
	});
	initForm();
}
function initSelectC(mid, fid){
	fid=fid||0;
	selectF.createSelect("${base}/system/module/"+mid+"/functions/list", {
		pageNo:1,pageSize:999,sortName:"id", sortOrder: "asc"
	},function(row){
		return [row.id, row.cell[1]+"["+row.cell[0]+":"+row.cell[4]+"]"];
	}, fid).change(function(){
		var text = $("#selectFunctions").find("option:selected").text();
		text = text.substring(0, text.indexOf("["));
		$("#input_menu_name").val(text);		
	});
	if(fid>0){
		$("#input_func_id").val(fid);
	}
	initedModuleId = mid;
}
var draggingNode = null;
var draggingParent = null;
var draggingPrev = null;
var draggingNext = null;

function undoDragNode(){
	var tree = $.fn.zTree.getZTreeObj("treeDemo");
	var type = null;
	var target = null;
	if(draggingPrev){
		type = "next";
		target = draggingPrev;
	}else
	if(draggingNext){
		type = "prev";
		target = draggingNext;
	}else
	if(draggingParent){
		type = "inner";
		target = draggingParent;
	}
	tree.moveNode(target, draggingNode, type, true);
	resetDrag();
}
function refreshMenuTree(id){
	var tree = $.fn.zTree.getZTreeObj("treeDemo");//$("#treeDemo"));
	var menuId = +$("#input_id").val();//新建时menuId为0，编辑时为非0
	id=+id||0;
	var name = $("#input_menu_name").val();
	name += "["+id+"]";
	var mcid = selectF.val();
	if(+mcid>0){
		var text = selectF.find("option:selected").text();
		var result = text.match(/\[.*?\]/);
		name += result[0];
	}
	if(menuId==0){//新建模式，添加一个节点
		var menu = {id: id, name: name, seq:nextSequence};
		var parent = parentNodeId==0?null:tree.getNodeByParam("id", parentNodeId);
		if(parent!=null){
			parent.subs++;
			menu.parent = parent.name;
		}
		menu.dropInner = !(+mcid>0);
		menu.parentElement = parent;
		menu.cId = +mcid;
		menu.subs = 0;
		tree.addNodes(parent, menu);
		//TODO: 应该在这里重置下一个新建节点的sequence，因为当前仍然在新建模式之下。
		nextSequence++;
		$("#input_sequence").val(nextSequence);
		
	}else{//编辑模式，修改节点
		var nodes = tree.getSelectedNodes();
		for(var i=0, len=nodes.length; i<len; i++) {//不要担心，只会循环一次，因为同时只会一个节点被选中
			var node = nodes[i];
			node.name = name;
			node.dropInner = !(+mcid>0);
			node.cId = +mcid;
			tree.updateNode(node);
		}
	}
}
function initForm(menu, subs){
	subs = subs||0;
	menu = menu||{id:0, name: "", desc: "", pid: parentNodeId, parent: parentNodeName, seq: nextSequence, mid: 0, mcid: 0};
	$("#input_id").val(menu.id);
	$("#input_owner_id").val(menu.pid);
	$("#input_func_id").val(menu.mcid);
	$("#input_menu_name").val(menu.name);
	$("#text_menu_desc").val(menu.desc);
	$("#input_owner").val(menu.parent);
	$("#input_sequence").val(menu.seq);
	if(subs>0){
		selectM.val(0);
		selectM.attr("disabled", true);
		selectF.val(0);
		selectF.attr("disabled", true);
	}else{
		selectM.attr("disabled", false);
		selectF.attr("disabled", false);
		selectM.val(menu.mid);
		if(initedModuleId==menu.mid){
			selectF.val(menu.mcid);
		}else
		if(menu.mid>0){
			initSelectC(menu.mid, menu.mcid);
		}else{
			selectF.val(0);
			selectF.attr("disabled", true);
		}
	}
}
function showEditMode(editFlag, subs){
	if(!!editFlag){
		$("#capNew").hide();
		$("#capEdit").show();
		if(!subs){
			$("#btDelete").show()
		}else{
			$("#btDelete").hide();
		}
	}else{
		$("#capNew").show();
		$("#capEdit").hide();
		initForm();
	}
}
function dropConfirm(treeNodes, targetNode, moveType){
	var node = treeNodes[0];
	var name = node.name;
	var target = targetNode.name;
	var content = ["你确认要将菜单","【"+ name + "】", "移动至","【"+target+"】"];
	if(moveType=="inner"){
		content.push("的下一层级？");
	}else
	if(moveType=="prev"){
		content.push("的前面？");
	}else
	if(moveType=="next"){
		content.push("的后面？");
	}
	art.dialog({
		title: "移动位置确认",
		icon: "question",
		content: content.join(""),
		width: 250,
		height: 150,
		background: '#EEE', // 背景色
		opacity: 0.05,	// 透明度
		lock: true,
		ok: function(){
			var id = node.id;
			var pId = node.pId;
			var prev = node.getPreNode();
			var next = node.getNextNode();
			var sequence = 0;
			if(!!prev){
				if(!!next){
					sequence = (prev.seq+next.seq)/2;
				}else{
					sequence = prev.seq + 1;
				}
			}else
			if(!!next){
				sequence = next.seq -1;
			}
			//alert("sequence="+sequence+", pre="+(!!prev?prev.seq:null)+", next="+(!!next?next.seq:null));
			node.seq = sequence;
			//if(false)
			$.post("${base}/${module}/position", {id: id, "scope.id": pId, sequence: sequence}, function(json){
				if(json.success){
					resetDrag();
				}else{
					undoDragNode();
				}
			});
		},
		cancel: function(){
			undoDragNode();
		}
	});
}
function resetDrag(){
	draggingNode = null;
	draggingParent = null;
	draggingPrev = null;
	draggingNext = null;
}
function removeItem(){
	var id = currentNodeId;
	art.dialog({
		content: "确定要删除该${moduleName}【id="+id+"】？",
		title: "确认删除",
		icon: "question",
		background: '#EEE', // 背景色
		opacity: 0.05,	// 透明度
		lock: true,
		button: [{
			name: "确定",
			callback: function(){
				$.post("${base}/${module}/remove", {id: id}, function(text){
					var result = text;
					if(result.success){
						var tree = $.fn.zTree.getZTreeObj("treeDemo");
						var currentNode = tree.getNodeByParam("id", id);
						var parentNode = currentNode.getParentNode();
						if(!!parentNode){
							parentNode.subs--;
						}
						tree.removeNode(currentNode);
						//应该清空当前节点的信息展示。并且，由于失去了当前节点，展示区不应该有任何内容==>显示初始的新建菜单。
						
						var nodes = tree.getNodes();
						var len = nodes.length;
						if(len>0){
				            var lastSub = nodes[len-1];
				            nextSequence = Math.ceil(+lastSub.seq)+1;
				        }else{
				            nextSequence = 0;
				        }
						initForm({id:0, name: "", desc: "", pid: 0, parent: "", seq: nextSequence, mid: 0, mcid: 0});
						$("#capNew").show();
				        $("#capEdit").hide();
					}else{
						art.dialog({
							title: "删除失败",
							icon: "error",
							content: result.err,
							width: 400,
							height: 250,
							background: '#EEE', // 背景色
							opacity: 0.05,	// 透明度
							lock: true,
							ok: true
						});
					}
				});
			}
		}, {
			name: "取消",
			focus: true
		}]
	});
}
//-->
</script>
</head>
<body>
<div>
<div style="width:230px;float: left;padding: 0 10px 10px 10px">
<ul id="treeDemo" class="ztree"></ul>
</div>
<div style="width:450px; height: auto; float: left;margin: 15px 10px 10px 10px; overflow: auto">
<div style="height: 40px" id="capNew">
<em style="font-size: 24;font-weight:bold">新建菜单</em>
</div>
<div style="height: 40px; display: none" id="capEdit">
<em style="font-size: 24;font-weight:bold">编辑菜单</em>
<input id="btNew" type="button" value="新建菜单" onclick="showEditMode()">
<input id="btDelete" type="button" value="删除菜单" onclick="removeItem()" style="color: red">
</div>
<div>
<form id="additemform" action="" method="POST">
<input type="hidden" id="input_id" name="id" value="">
<input type="hidden" id="input_owner_id" name="scope.id" value="">
<input type="hidden" id="input_func_id" name="reference.id" value=""/>
<input type="hidden" id="input_sequence" name="sequence" value=""/>
<table width="100%">
<tr>
<th style="width:60px">名称:</th>
<td><input type="text" id="input_menu_name" name="name" value=""/></td>
</tr>
<tr>
<th style="width:60px">描述:</th>
<td><textarea id="text_menu_desc" rows="3" cols="35" name="description"></textarea></td>
</tr>
<tr>
<th style="width:60px">父菜单:</th>
<td><input type="text" id="input_owner" value="" disabled/></td>
</tr>
<tr>
<th style="width:60px">功能:</th>
<td>
<select id="selectModules" style="width: 150px">
	<option value="0">--请选择模块--</option>
</select>
<select id="selectFunctions" style="width: 250px">
	<option value="0">--请选择功能--</option>
</select>
</td>
</tr>
<tr>
</tr>
</table>
<input type="submit" value="保存" id="btadditem">
</form>
</div>
</div>
		
</div>
</body>
</html>